<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Goods_model extends My_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->model_name="ĺĺ";
        $this->tablename="goods";
    }

    public function getcombinegoods($ids)
    {
        $idstring=implode(",",$ids);
        $return = [];
        $where='id in ('.$idstring.') and delete=0';
        $products = $this->get_items_by_where($where);
        foreach($products as $p)
        {
            $p["option"]=unserialize($p["option"]);
            if($p["option"] && isset($p["option"]["vv"]) && count($p["option"]["vv"])>2)
            {
                $return[]=$p;
            }
        }
        return $return;
    }

    public function getallgoodsids($ids){
        $where='id in ('.$ids.') and delete=0';
        return $this->get_items_by_where($where);
    }


    public function push($id){
        $this->db->where(array('id'=>$id));
        $this->db->set('push','push + 1',FALSE);
        $this->db->update($this->tablename);
    }
    
    public function getrandgoods($num)
    {
        $sql="select * from ".$this->table_prefix.$this->tablename." where `delete`=0 and (id >= ((SELECT MAX(id) FROM ".$this->table_prefix.$this->tablename.")-(SELECT MIN(id) FROM ".$this->table_prefix.$this->tablename.")) * RAND() + (SELECT MIN(id) FROM ".$this->table_prefix.$this->tablename.")) limit ".$num;
        $query=$this->db->query($sql);
        $data=$query->result_array();
        return $data;
    }

    public function getallgoodbypage($page,$size)
    {

        $offset=$size*($page-1);
        $query=$this->db->select("id,price")->limit($size, $offset)->order_by('id asc')->get($this->table_prefix.$this->tablename);
        $items=$query->result_array();
        if($items){
            return $items;
        }else{
            return false;
        }

    }

    public function getallgoodsbypage($shopid,$timelimit=array(),$page,$size,$maxid=0){
        
        if($timelimit && isset($timelimit["start"]) && isset($timelimit["end"]))
        {
            $where="delete=0 and catid={$shopid} and addtime between '".$timelimit["start"]."' and '".$timelimit["end"]."'";
            if($maxid>0) $where.=" and id>".$maxid;            
        }
        else
        {
            $where=array("delete"=>0,"catid"=>$shopid);
            if($maxid>0)    $where["id >"]=$maxid;
        }
        return $this->get_items_by_where_page($where,$page,$size);
    }

    public function getallgoodsoption($shopid)
    {
        $where=array("delete"=>0,"catid"=>$shopid);
        $query=$this->db->select("id,option")->where($where)->get($this->table_prefix.$this->tablename);
        $items=$query->result_array();
        return $items;

    }

    public function get_range($shopid,$offset=0,$num=100)
    {
        $where=array("delete"=>0,"catid"=>$shopid);
        $query=$this->db->where($where)->limit($num, $offset)->order_by("id asc")->get($this->table_prefix.$this->tablename);
        $items=$query->result_array();
        if($items){
            return $items;
        }else{
            return false;
        }
    }

    public function get_bykey($shopid,$keys)
    {
        if(empty($keys)) return false;
        $where=array("delete"=>0,"catid"=>$shopid);
        $key=explode(",",$keys);
        $icount=0;
        $this->db->group_start();
        foreach($key as $vv)
        {
            if($icount>0)
            {
                $this->db->or_like("name", $vv);
            }
            else
            {
                $this->db->like("name", $vv);
            }
            $icount++;
        }
        $this->db->group_end();
        $query=$this->db->where($where)->from($this->table_prefix.$this->tablename)->order_by("id asc")->get();
        $items=$query->result_array();
        if($items){
            return $items;
        }else{
            return false;
        }
    }


    public function getallgoods($shopid,$timelimit=array(),$filed="*"){
        
        if($timelimit && isset($timelimit["start"]) && isset($timelimit["end"]))
        {
            $where="delete=0 and catid={$shopid} and addtime between '".$timelimit["start"]."' and '".$timelimit["end"]."'";
        }
        else
        {
            $where=array("delete"=>0,"catid"=>$shopid);
        }
        return $this->get_items_by_where($where,"id desc",$filed);
    }


    public function getproductcount($catid,$done=0)
    {
        $where=["delete"=>0,"catid"=>$catid];
        if($done>0)
        {
            $where["push >"]=0;
        }
        $count=$this->getcount($where);
        return $count;
    }

    public function getlasttime($catid)
    {
        $query=$this->db->select('addtime')->where(['delete'=>0,"catid"=>$catid])->limit(1)->order_by("id asc")->get($this->table_prefix.$this->tablename);
        $item=$query->row_array();
        if($item)
        {
            return $item["addtime"];
        }
        else
        {
            return "no data";
        }
    }
    

    public function search_good($key,$catid=0)
    {      
        $where=["name"=>$key,"delete"=>0];
        if($catid>0)
        {
            $where["catid"]=$catid;
        }
        $query=$this->db->where($where)->get($this->table_prefix.$this->tablename);
        $item=$query->row_array();
        if($item){
            return $item;
        }else{
            return false;
        }
    }

    public function get_type($catid)
    {
        $where=["delete"=>0,"collection !="=>"","catid"=>$catid];
        $query=$this->db->select('collection')->where($where)->distinct('collection')->get($this->table_prefix.$this->tablename);
        $item=$query->result_array();
        if($item){
            return $item;
        }else{
            return false;
        }
    }

    public function get_items_by_where_fix($where)
    {
        return $this->get_items_by_where($where);
    }

    private function pre_filter_where($filter)
    {

        $where="`delete`=0";

        if(isset($filter["ids"]) && $filter["ids"])
        {
            $where.=" and id in (".$filter["ids"].")";
        }

        if(isset($filter["gcatid"]) && $filter["gcatid"]>0)
        {
            $where.=" and catid=".$filter["gcatid"];
        }

        if(isset($filter["gcatid"]) && $filter["gcatid"]==0)
        {
            $where.=" and sellcount>0";
        }

        if(isset($filter["price_min"]) && isset($filter["price_max"]) && $filter["price_min"] && $filter["price_max"])
        {
            $where.=" and price>".$filter["price_min"]." and price<".$filter["price_max"];
        }

        if(isset($filter["push"]) && $filter["push"]>0)
        {
            if($filter["push"]>=5){
                $where.=" and push>3";
            }
            else
            {
                $where.=" and push=".($filter["push"]-1);

            }
        }

        if(isset($filter["collection"]) && $filter["collection"])
        {
            $where.=" and collection='".$filter["collection"]."'";
        }

        if(isset($filter["alicategory"]) && $filter["alicategory"])
        {
            $where.=" and rcatid in (".$filter["alicategory"].")";
        }

        if(isset($filter["pastday"]) && $filter["pastday"])
        {
            $where.=" and DATEDIFF(addtime,NOW())>=-".$filter["pastday"];
        }
        

        if(isset($filter["sesson"]) && $filter["sesson"])
        {
            $map=["春","夏","秋","冬"];
            $sesson=$map[$filter["sesson"]-1];
            $where.=" and FIND_IN_SET('".$sesson."',`session`)>0 ";
        }

        if(isset($filter["keyword"]) && $filter["keyword"])
        {
            $sq = $this->db->escape('[[:<:]]'.strtolower($filter["keyword"]).'[[:>:]]');
            $where .=" and name REGEXP ".$sq;

            //$where.=" and MATCH(name) AGAINST ('".$filter["keyword"]."')";
        }

        return $where;

    }

    public function addpushcount($gid)
    {
        $this->auto_add("push",["id"=>$gid]);
    }

    public function addsell($id,$num)
    {
        $this->auto_add("sellcount",["id"=>$id],$num);
    }

    public function get_filter_goods($filter)
    {
        $where = $this->pre_filter_where($filter);

        if(isset($filter["limits"]) && $filter["limits"]>0)
        {
            $offset=$filter["startindex"]-1;

            if(strstr($where,"REGEXP"))
            {
   	            $query=$this->db->where($where,"",false)->limit($filter["limits"], $offset)->order_by('id asc')->get($this->table_prefix.$this->tablename);
            }
            else
            {
            	$query=$this->db->where($where)->limit($filter["limits"], $offset)->order_by('id asc')->get($this->table_prefix.$this->tablename);
            }
            $data=$query->result_array();
        }
        else 
        {
            $data = $this->get_items_by_where($where);
        }

        return $data;
    }

    public function getfiltercount($filter)
    {
        $where = $this->pre_filter_where($filter);        
        $total = $this->getcount($where);
        if(isset($filter["limits"]) && $filter["limits"]>0)
        {
            if(($filter["startindex"]+$filter["limits"])>$total)
            {
                if($filter["startindex"]>$total)
                {
                    return 0;
                }
                else {                    
                    return $total-$filter["startindex"]+1;
                }
            } else {
                return $filter["limits"];
            }
        }

        return $total;
    }

    public function getpage($shopid,$page,$key='',$filter=[],$pagesize=0,$maxid=0){
        if($pagesize>0)
        {
            $this->pagesize=$pagesize;
        }
        /*
        if($this->adminid && !$this->ion_auth_acl->has_permission("allshop"))
        {
            $query=$this->db->where(array("id"=>$shopid))->get($this->table_prefix."category");
            $shop=$query->row_array();            
            if(empty($shop)||$shop["adminid"]!=$this->adminid)
            {
                return array('data'=>array(),'pager'=>'','total'=>0,'pages'=>0);                
            }
        }
        */
        if($shopid>0)
        $where="catid=".$shopid." and `delete`=0";
        else
        $where="`delete`=0 and sellcount>0";

        //echo $where;
        //die();

        if($maxid>0)
        {
            $where.=" and id>".$maxid;
        }
        if(isset($filter["price_min"]) && isset($filter["price_max"]) && $filter["price_min"] && $filter["price_max"])
        {
            $where.=" and price>".$filter["price_min"]." and price<".$filter["price_max"];
        }

        if(isset($filter["push"]) && $filter["push"]>0)
        {
            if($filter["push"]>=5){
                $where.=" and push>3";
            }
            else
            {
                $where.=" and push=".($filter["push"]-1);

            }
        }

        if(isset($filter["collection"]) && $filter["collection"])
        {
            $where.=" and collection='".$filter["collection"]."'";
        }

        if(isset($filter["alicategory"]) && $filter["alicategory"])
        {
            $where.=" and rcatid in (".$filter["alicategory"].")";
        }
        
        if(isset($filter["pastday"]) && $filter["pastday"])
        {
            $where.=" and DATEDIFF(addtime,NOW())>=-".$filter["pastday"];
        }
        

        if(isset($filter["sesson"]) &&  $filter["sesson"])
        {
            $map=["春","夏","秋","冬"];
            $sesson=$map[$filter["sesson"]-1];
            $where.=" and FIND_IN_SET('".$sesson."',`session`)>0 ";
        }

        if(is_numeric($key))
        {
            $where=["id"=>$key];
            $key="";
        }else if($key)
        {
            $sq = $this->db->escape('[[:<:]]'.strtolower($key).'[[:>:]]');
            $where .=" and name REGEXP ".$sq;
            //$where .=" and MATCH(name) AGAINST ('".$key."')"; 
            $key="";
        }

        /*
        $join=array(
            "table"=>"tb_push_log",
            "where"=>"tb_goods.id = tb_push_log.productid",
            "pattern"=>"left"
        );
        */
        #$cols="tb_goods.id,name,source,source_url,price,sales,tb_goods.addtime,tb_push_log.returnid as rid";
        #$cols="id,name,source,source_url,price,sales,addtime,edittime,thumb,option,push,oname,desc,desc2";

        $cols="*";
        $join=array();
        if(!isset($filter["sort"]))
        {
            $filter["sort"]="id_desc";
        } 
        $sort=str_replace("_"," ",$filter["sort"]);

        $data = $this->get_items_by_page($where,$page,'backend/products/pagelist/'.$shopid,$this->table_prefix.$this->tablename.".".$sort,$join,$key,$cols);
        return $data;

    }


    public function getbyid($id){
        $where=array("delete"=>0,"id"=>$id);
        return $this->get_item_by_where($where);
    }

    public function getbytbid($iid,$shopid=0,$sitename=""){
        $where=array("delete"=>0,"tbid"=>$iid,"catid"=>$shopid);
        if($sitename)
        {
            $where["source"]=$sitename;
        }
        return $this->get_item_by_where($where);
    }

    public function create($data){
        if(!isset($data["addtime"])){
            $data["addtime"]=date("Y-m-d H:i:s");
        }
        return $this->add_item($data);     
    }
    
    public function getitemsfilter($filter)
    {
        return $this->get_items_by_where($filter);
    }

    public function delitem($id)
    {
        if(is_array($id))
        {
            $where="id in (".implode(",",$id).")";
        }
        else
        {
            $where=["id"=>$id];
        }
        $this->delete($where);
        return true;
    }
    

    public function update($id,$data){
        if(is_array($id))
        {
            $where="id in (".implode(",",$id).")";
        }else{
            $where=array("id"=>$id);
        }
        return $this->update_item($where,$data);
    }
    
}